<template>
  <div class="default-main ba-table-box">
    <!-- 表格顶部菜单 -->
    <TableHeader
      :buttons="[
        'refresh',
        'add',
        'edit',
        'remove',
        'comSearch',
        'columnDisplay',
      ]"
      :quick-search-placeholder="placeholder"
      @action="baTable.onTableHeaderAction"
    />
    <!-- 表格 -->
    <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
    <Table ref="tableRef" :pagination="false" @action="baTable.onTableAction" />
    <!-- 表单 -->
    <PopupForm
      v-if="baTable.form.operate ? true : false"
      :menus="state.menus"
      ref="formRef"
    />
  </div>
</template>
<script setup lang="ts">
import { ref, provide, onMounted, reactive, markRaw } from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff } from "@/utils/common"; // 导入表格api方法生成器
import { sysMRole } from "@/api/backend/index";
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import PopupForm from "./popupForm.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { ElForm } from "element-plus";
import type { TableColumn, TableRow } from "@/utils/baTable"; //表格列行类型
import { useRole } from "@/store/backend/SysM/role";
import { cloneDeep } from "lodash";
import DatePick from "@/components/datePicker/index.vue";
import { useRoute } from "vue-router";
import { useNavTabs } from "@/store/navTabs";

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const role = useRole();
const formRef = ref();
const route = useRoute();
const navTabs = useNavTabs();

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + sysMRole)
      ? (navTabs as any).pageSizeMap.get(route.path + sysMRole)
      : 10;
  }
  return 10;
};

const state: { menus: anyObj[] } = reactive({ menus: [] });
const baTable = new baTableClass(
  new baTableApi(sysMRole), //this.api = api角色管理
  {
    expandAll: true,
    pk: "roleId",
    column: [
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("roleId"),
        label: "角色编号",
        prop: "roleId",
        align: "left",
        operatorPlaceholder: "精确搜索",
      },
      {
        show: filedShowOff("roleName"),
        label: "角色名称",
        prop: "roleName",
        align: "left",
        operatorPlaceholder: "模糊查询",
      },
      {
        show: filedShowOff("roleKey"),
        label: "权限字符",
        prop: "roleKey",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("roleSort"),
        label: "显示顺序",
        prop: "roleSort",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("status"),
        label: "状态",
        prop: "status",
        align: "center",
        render: "switch",
        replaceValue: {
          "0": "正常",
          "1": "停用",
        },
      },
      //   {
      //     label: "更新时间",
      //     prop: "updatetime",
      //     align: "center",
      //     width: "160",
      //     render: "datetime",
      //     operator: false,
      //   },
      {
        show: filedShowOff("createTime"),
        label: "创建时间",
        prop: "createTime",
        align: "center",
        width: "160",
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(DatePick),
        // render: "datetime",
        // operator: "RANGE",
      },
      {
        show: operatorShowOff([route.path + "/edit", route.path + "/remove"]),
        label: "操作",
        align: "center",
        width: "130",
        operator: false,
        render: "buttons",
        fixed: "right",
        buttons: [
          {
            render: "tipButton",
            name: "editRole", //与edit绑定
            title: "编辑",
            text: "",
            type: "primary",
            icon: "iconfont icon-pencil",
            class: "table-row-edit",
            display: (row: TableRow, field: TableColumn) => {
              if (row.admin) {
                return false;
              }
              return true;
            },
            disabledTip: false,
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "confirmButton",
            name: "remove",
            title: "删除",
            text: "",
            type: "danger",
            icon: "el-icon-DeleteFilled",
            class: "table-row-delete",
            popconfirm: {
              confirmButtonText: "删除",
              cancelButtonText: "取消",
              confirmButtonType: "danger",
              title: "确定删除所选项吗",
            },
            display: (row: TableRow, field: TableColumn) => {
              if (row.admin) {
                return false;
              }
              return true;
            },
            disabledTip: false,
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
      },
    ],
    filter: {
      pageSize: pageSizeKeep(),
    },
  },
  {
    defaultItems: {
      status: "0",
      roleId: undefined,
      roleName: undefined,
      roleKey: undefined,
      roleSort: 0,
      menuIds: [],
      deptIds: [],
      menuCheckStrictly: true,
      deptCheckStrictly: true,
      remark: undefined,
    },
  },
  {
    // 提交前
    onSubmit: (params: { formEl: InstanceType<typeof ElForm> }) => {
      var items = cloneDeep(baTable.form.items!);

      items.menuIds = formRef.value.getCheckeds();
      console.log("items", items);

      for (const key in items) {
        if (items[key] === null) {
          delete items[key];
        }
      }

      // 表单验证通过后执行的api请求操作
      let submitCallback = () => {
        baTable.form.submitLoading = true;
        baTable.api
          .postData(baTable.form.operate!, items)
          .then((res) => {
            baTable.onTableHeaderAction("refresh", {});
            baTable.form.submitLoading = false;
            baTable.form.operateIds?.shift();
            if (baTable.form.operateIds!.length > 0) {
              baTable.toggleForm("edit", baTable.form.operateIds);
            } else {
              baTable.toggleForm();
            }
            baTable.runAfter("onSubmit", { res });
          })
          .catch((err) => {
            baTable.form.submitLoading = false;
          });
      };

      if (params.formEl) {
        baTable.form.ref = params.formEl;
        params.formEl.validate((valid) => {
          if (valid) {
            submitCallback();
          }
        });
      } else {
        submitCallback();
      }
      return false;
    },
  }
);

onMounted(() => {
  const { proxy } = useCurrentInstance();

  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(sysMRole);

  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      console.log("data", data);
      //编辑角色的权限功能 editRole避免被其他页面触发
      if (data.name == "editRole") {
        role
          .getRoleIdKeys(data.row)
          .then((res: any) => {
            state.menus = res.checkedKeys;
            //这里触发toggle的方法，将id传入
            baTable.toggleForm("edit", [data.row.roleId]);
          })
          .catch((err) => {
            console.log(err);
          });
      }
      //   // onRollback([data.row[baTable.table.pk!]])
      // } else if (data.name == '查看') {
      //   // 主键字段 pk: "id",
      //   editButtonClick(data.row[baTable.table.pk!])
      // }
    }
  );
});

// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
</script>
<style lang="scss" scoped>
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 60px var(--ba-main-space);
}

.ceshi {
  width: 200px;
  height: 200px;
  background: rgb(210, 210, 40);
  color: white;
}
</style>
